﻿#include "datamanager.h"
#include "ui_datamanager.h"
#include "qpainter.h"
#include "DataBase/mysql.h"
#include "Beans/datainfobean.h"
#include "QDate"
#include "QJsonArray"
#include "qjsonobject.h"
#include "QJsonDocument"
#include "DataPro/datapro.h"
#include "Report/printreport.h"
#include "dialog/myhelper.h"
#include "Report/individualreport.h"
#include "constant.h"


DataManager::DataManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataManager)
{
    ui->setupUi(this);
    ui->lineEdit_Year->setValidator(new QIntValidator(ui->lineEdit_Year));
    ui->lineEdit_Month->setValidator(new QIntValidator(ui->lineEdit_Month));
    ui->lineEdit_Day->setValidator(new QIntValidator(ui->lineEdit_Day));
    initTableView();
    ui->pushButton_Delete->setEnabled(false);
    ui->lineEdit_Content->setText("");
    QDate cdate = QDate::currentDate();
    ui->lineEdit_Year->setText(cdate.toString("yyyy"));
    ui->lineEdit_Month->setText(cdate.toString("MM"));
    ui->lineEdit_Day->setText(cdate.toString("dd"));
    QueryDataBase();
    if(Constant::ShowFullScreen)
        this->showFullScreen();


}

DataManager::~DataManager()
{
    delete ui;
}

void DataManager::QueryDataBase()
{
    QString file=Constant::DataBasePath;
    Qt::HANDLE threadId = QThread::currentThreadId();
    QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

    MySql *mySql = new MySql(file,threadIdStr);
    dibs=mySql->DataQueryAll();

    int dataLen=dibs.size();
    if(dataLen>0)
    {
        for(int i=0;i<dataLen;i++)
        {
            DATAINFO_TABLE_DATA data;
            data.TaskID=dibs.at(i).TaskID;
            data.TaskType=dibs.at(i).TaskType;
            data.TaskTheme=dibs.at(i).Theme;
            data.TaskContent=dibs.at(i).Content;
            data.MeasureTime=dibs.at(i).MeasureTime;
            data.dib=dibs.at(i);
            m_dataInfoTableHash.insert(data.MeasureTime,data);
        }
        RefreshTable();
    }
}
void DataManager::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(rect(),QPixmap(":/images/share/selectmodel_page_bg2.png"),QRect());
}

void DataManager::on_pushButton_exit_clicked()
{
    this->close();
}

void DataManager::initTableView()
{
    //自定义表头操作
    m_pTableHeader = new TableViewHeader(Qt::Horizontal, this);//表头
    m_pTableHeader->setStretchLastSection(true);//表头最后一列填充
    ui->tableView->setHorizontalHeader(m_pTableHeader);//设置表头
    ui->tableView->verticalHeader()->setFont(QFont( "黑体", 22, QFont::Black ));


    //创建model（目前使用的是标准数据模型，可以自定义数据模型），绑定model
    m_pTableModel = new QStandardItemModel(this);
    ui->tableView->setModel(m_pTableModel);//设置model
    ui->tableView->verticalHeader()->hide();


    //创建表头信息
    QStringList headerList;
    headerList << " " << tr("序号")   << tr("任务")<< tr("模式") << tr("主题") << tr("内容") << tr("时间");
    m_pTableModel->setHorizontalHeaderLabels(headerList);


    //单击
    connect(ui->tableView, &QTableView::clicked,this, &DataManager::on_tableViewClick);
    //双击
    connect(ui->tableView, &QTableView::doubleClicked,this, &DataManager::on_tableViewDbClick);

    //标题头排序
    connect(ui->tableView->horizontalHeader(), &QHeaderView::sectionClicked,this, &DataManager::on_tableViewSort);
    //全选
    connect(m_pTableHeader, &TableViewHeader::stateChanged,this, &DataManager::on_tableViewSelectAllCheckBoxClick);

    //设置列宽
    setColumnWidth();

}
/*************************
 * QTableView-单击事件
 * ***********************/
void DataManager::on_tableViewClick(QModelIndex nIndex)
{


    int nRow = nIndex.row();
    int nCol = nIndex.column();

    Qt::CheckState oldState = m_pTableModel->item(nRow, COLUMN_CHECKBOX)->checkState();
    Qt::CheckState newState;

    if(oldState == Qt::Unchecked)
    {
        newState = Qt::Checked;
        m_nCheckedCount++;
    }
    else
    {
        newState = Qt::Unchecked;
        m_nCheckedCount--;
    }
    m_pTableModel->item(nRow, COLUMN_CHECKBOX)->setCheckState(newState);

    if(newState == Qt::Unchecked || m_nCheckedCount == m_pTableModel->rowCount())
    {
        m_pTableHeader->onStateChanged(newState);//改变标题栏的全选状态
    }
    if(m_nCheckedCount>0)
        ui->pushButton_Delete->setEnabled(true);
    else
        ui->pushButton_Delete->setEnabled(false);
}

/*************************
 * QTableView-双击事件
 * ***********************/
void DataManager::on_tableViewDbClick(QModelIndex nIndex)
{


    int row = nIndex.row();

    qDebug() << "Db Click row:" << row;
}
/*************************
 * QTableView-排序
 * ***********************/
void DataManager::on_tableViewSort(int nColumn)
{

    //点击表头实现排序
//    ui->tableView->horizontalHeader()->setSortIndicatorShown(true);
//    ui->tableView->sortByColumn(nColumn,Qt::SortOrder::AscendingOrder);
}
/*************************
 * QTableView-响应表头全选操作
 * ***********************/
void DataManager::on_tableViewSelectAllCheckBoxClick(Qt::CheckState state)
{
    int nRowCount = m_pTableModel->rowCount();//当前行数

    for(int i = 0; i < nRowCount; i++)
    {
        m_pTableModel->item(i, COLUMN_CHECKBOX)->setCheckState(state);
    }
}

/*************************
 * QTableView-设置列宽
 * ***********************/
void DataManager::setColumnWidth()
{
    ui->tableView->setColumnWidth(COLUMN_CHECKBOX,150);
    ui->tableView->setColumnWidth(COLUMN_NO,150);
    ui->tableView->setColumnWidth(COLUMN_ID, 500);
    ui->tableView->setColumnWidth(COLUMN_TYPE, 300);
    ui->tableView->setColumnWidth(COLUMN_THEME, 300);
    ui->tableView->setColumnWidth(COLUMN_CONTENT, 300);
    ui->tableView->setColumnWidth(COLUMN_MEASURETIME, 400);

}

void DataManager::RefreshTable()
{
    if(m_pTableModel->rowCount() > 0)
    {
        m_pTableModel->removeRows(0, m_pTableModel->rowCount());
    }

    QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
    int row = 0;
    for(; i != m_dataInfoTableHash.end(); ++i)
    {
        DATAINFO_TABLE_DATA data = i.value();

        //可以通过insertRow和setData增加数据
        m_pTableModel->insertRow(row, QModelIndex());
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_CHECKBOX), "");
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_NO), row+1);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_ID), data.TaskID);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_TYPE), data.TaskType);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_THEME), data.TaskTheme);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_CONTENT), data.TaskContent);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_MEASURETIME), data.MeasureTime);


        //也可以通过setItem增加数据
        //m_pTableModel->setItem(row, COLUMN_CHECKBOX, new QStandardItem(""));

        // 设置全部列居中显示
        for(int j = COLUMN_NO; j <= COLUMN_MEASURETIME; j++)
        {
            m_pTableModel->item(row, j)->setTextAlignment(Qt::AlignCenter);
        }
        row++;
    }
}

void DataManager::on_pushButton_Query_clicked()
{
    QString year=ui->lineEdit_Year->text();
    QString month=ui->lineEdit_Month->text();
    if(month.size()==1)
        month="0"+month;
    QString day=ui->lineEdit_Day->text();
    if(day.size()==1)
        day="0"+day;
    QString Content=ui->lineEdit_Content->text();
    QString time=year+"-"+month+"-"+day;

    m_dataInfoTableHash.clear();
    QString file=Constant::DataBasePath;
    Qt::HANDLE threadId = QThread::currentThreadId();
    QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

    MySql *mySql = new MySql(file,threadIdStr);
    dibs=mySql->DataQueryBy(Content,time);

    int dataLen=dibs.size();
    if(dataLen>0)
    {
        for(int i=0;i<dataLen;i++)
        {
            DATAINFO_TABLE_DATA data;
            data.TaskID=dibs.at(i).TaskID;
            data.TaskType=dibs.at(i).TaskType;
            data.TaskTheme=dibs.at(i).Theme;
            data.TaskContent=dibs.at(i).Content;
            data.MeasureTime=dibs.at(i).MeasureTime;
            data.dib=dibs.at(i);
            m_dataInfoTableHash.insert(data.MeasureTime,data);
        }

    }
    RefreshTable();
}


void DataManager::on_pushButton_Print_clicked()
{
    QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
    int row=0;
    DataPro dataPro;
    int selRow=0;
    for(; i != m_dataInfoTableHash.end(); ++i)
    {
        DATAINFO_TABLE_DATA data = i.value();
        if(m_pTableModel->item(row,0)->checkState()==Qt::Checked)
        {
            PrintReport pr(data);
//            QString groupType=m_pTableModel->item(row,COLUMN_TYPE)->text();
//            if(groupType=="对抗模式")
//                pr.Report_battle();
//            else
//                pr.Report_group();
            selRow++;
        }
        row++;
    }
    if(selRow>0)
        myHelper::ShowMessageBoxInfo(QString("%1条数据导出成功！").arg(QString::number(selRow)));
    else
        myHelper::ShowMessageBoxInfo("您未选中需要导出的行！");
}


void DataManager::on_pushButton_Delete_clicked()
{
    //删除
    bool b=myHelper::ShowMessageBoxQuesion("确认要删除被选中的数据吗？");
    if(b)
    {
        QString file=Constant::DataBasePath;
        Qt::HANDLE threadId = QThread::currentThreadId();
        QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

        MySql *mySql = new MySql(file,threadIdStr);
        QHashDataInfoTableIterator i = m_dataInfoTableHash.begin();
        int row=0;
        int selRow=0;
        for(; i != m_dataInfoTableHash.end(); ++i)
        {
            DATAINFO_TABLE_DATA data = i.value();
            if(m_pTableModel->item(row,0)->checkState()==Qt::Checked)
            {
                mySql->MyDataDelete(m_pTableModel->item(row,COLUMN_MEASURETIME)->text());
                m_dataInfoTableHash.remove(m_pTableModel->item(row,COLUMN_MEASURETIME)->text());
                selRow++;
            }
            row++;
        }
        if(selRow>0)
        {
            RefreshTable();
            myHelper::ShowMessageBoxInfo("删除成功！");
        }else
        {
            myHelper::ShowMessageBoxInfo("您未选中需要修改的行！");
        }



        delete mySql;
    }

}


void DataManager::on_pushButton_clicked()
{
    IndividualReport w;
    DataBean db;
    db.UserID="admin";
    w.setV(db);
    QPrinter printer;
    QString fileName = "C:\\Users\\haibi\\Desktop\\个体报告.pdf";
    if (!fileName.isEmpty()) {
        // 如果文件后缀为空，则默认使用.pdf
        if (QFileInfo(fileName).suffix().isEmpty())
            fileName.append(".pdf");
        printer.setOutputFileName(fileName);
        printer.setResolution(300);
        printer.setPageMargins(QMarginsF(0, 0, 0, 0));

        QPixmap pixmap=w.grab(w.rect()); //抓取界面widget区域，可以抓取任意控件区域，Qt5推荐新的API QWidget::grab
        QPainter painter;
        painter.begin(&printer);
        painter.drawPixmap(0,0,pixmap); //按照坐标画图
        // printer.setPageSize(QPrinter::A4);
        //printer.setPageSize(QPageSize::A4);
        //        printer.setOutputFormat(QPrinter::PdfFormat);
        #ifdef X86
            printer.setPageSize(QPageSize::A4);
        #elif defined ARM
            printer.setPageSize(QPrinter::A4);
        #endif

    }
}

